<template>
	<view class="content">
		<view class="padding" v-show="!voicePath">
			<lsj-upload ref="lsjUpload" childId="upload1" :width="width" :height="height" :option="option" :size="size"
				:formats="formats" :instantly="false" @uploadEnd="onuploadEnd" @progress="onprogre" @change="change">
				<view class="btn" :style="{width: width,height: height}">选择附件</view>
			</lsj-upload>
		</view>


		<view class="padding">

			<view>已选择文件列表：</view>

			<view v-for="(item,index) in files.values()" :key="index">
				<text>选择的文件：{{item.name}}</text>
				<text @click="resetUpload(item.name)" v-if="item.type=='fail'"
					style="margin-left: 10rpx;padding: 0 10rpx;border: 1rpx solid #007AFF;">重新上传</text>
				<text @click="clear(item.name)"
					style="margin-left: 10rpx;padding: 0 10rpx;border: 1rpx solid #007AFF;">删除</text>
			</view>
		</view>
		<view class="btnBox">
			<view class="btn cfff btn1" @click="playVoice">
				{{isplay?'暂停播放':'播放音频'}}
			</view>
			<view class="btn cfff btn2" @click="submit">
				提交音频
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				option: {
					url: this.$url + 'mobile/index/uploadstream',
					name: 'file',
					header: {},
					formData: {
						file_type: ''
					}
				},
				width: '180rpx',
				height: '80rpx',
				formats: 'MP3,WAV,WMA,MP2,Flac,MIDI,RA,APE,AAC,CDA,MOV,M4A',
				size: 30,
				count: 1,
				files: new Map(),
				voicePath: '',
				isplay: false,
				ossInfo: {}
			}
		},
		mounted() {
			var deviceId;
			uni.getSystemInfo({
				success: function(res) {
					deviceId = res.deviceId
				}
			});
			this.option.header = {
				'Authorization': uni.getStorageSync('token'),
				'deviceId': deviceId,
				"Content-Type": "application/octet-stream",
			}
			this.init()
		},
		onReady() {},
		methods: {
			init() {
				console.log(111);
				this.innerAudioContext = uni.createInnerAudioContext()
				// this.innerAudioContext.autoplay = true;

				console.log(this.recorderManager, '111');
				this.recorderManager.onStop((res) => {
					console.log('recorder stop' + JSON.stringify(res));
					this.voicePath = res.tempFilePath;
				});
			},
			/**
			 * 某文件上传结束回调(成功失败都回调)
			 * @param {Object} item 当前上传完成的文件
			 */
			onuploadEnd(item) {
				uni.hideLoading()
				let res = JSON.parse(item.responseText)
				console.log('url', res.data.url);
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);
				this.$tools.toast(res.msg);
				this.voicePath = res.data.url
				// 更新当前窗口状态变化的文件
				this.files.set(item.name, item);
				// 强制更新视图
				this.$forceUpdate();
			},
			/**
			 * 上传进度回调
			 * 如果网页上md文档没有渲染出事件名称onprogre，请复制代码的小伙伴自行添加上哈，没有哪个事件是只(item)的
			 * @param {Object} item 当前正在上传的文件
			 */
			onprogre(item) {
				// 更新当前状态变化的文件
				this.files.set(item.name, item);
				console.log('打印对象', JSON.stringify(this.files.get(item.name)));
				// 强制更新视图
				this.$forceUpdate();
			},
			/**
			 * 文件选择回调
			 * @param {Object} files 已选择的所有文件Map集合
			 */
			change(files) {
				console.log(files.values());
				console.log('当前选择的文件列表：', JSON.stringify([...files.values()]));
				let arr = [...files.values()]
				console.log(arr[0]);
				var deviceId;
				uni.getSystemInfo({
					success: function(res) {
						deviceId = res.deviceId
					}
				});
				console.log(1111);
				/* uni.uploadFile({
					url: this.$url + 'mobile/index/uploadstream', //仅为示例，非真实的接口地址
					filePath: arr[0].path,
					name: 'file',
					header: {
						deviceId,
						'Authorization': uni.getStorageSync('token'),
					},
					formData: {
						'file_type': 'm4a'
					},
					success: (uploadFileRes) => {
						console.log(uploadFileRes.data);
					},
					fail: (err) => {
						console.log('err', err);
					}
				}); */

				if (arr.length) {
					// uni.showLoading({
					// 	title: '上传中'
					// })
					let date = this.$tools.formatDate(new Date())
					date = date.slice(0, date.indexOf(' '))
					let key = `public/upload/audio/${date}/${arr[0].name}`
					// let key = `audio/${date}/${arr[0].name}`
					console.log('key', key);

					let data = {
						dir: key
					}
					this.$api.ossSign(data).then(res => {
						console.log('data', res);
						uni.hideLoading();
						if (res.code == 200) {
							this.ossInfo = res.data
							uni.uploadFile({
								url: 'https://yqpeisong.oss-cn-beijing.aliyuncs.com', // 开发者服务器的URL。
								filePath: arr[0].path,
								name: 'file', // 必须填file。
								formData: {
									key,
									policy: this.ossInfo.policy,
									OSSAccessKeyId: this.ossInfo.accessid,
									signature: this.ossInfo.signature,
								},
								success: (res) => {
									console.log('aaa', res);
									if (res.statusCode === 204) {
										console.log('上传成功');
										console.log(this.active);
										uni.hideLoading();
									}
								},
								fail: err => {
									console.log(err, 'err');
								}
							});
						}
					})
				}
				// this.uplaod()

				// 更新选择的文件 
				this.files = files;
				// 强制更新视图
				this.$forceUpdate();
			},
			uplaod() {
				this.$refs['lsjUpload'].upload();
			},
			playVoice() {
				console.log('播放录音', this.innerAudioContext);
				console.log(this.voicePath);

				if (this.voicePath) {
					if (this.isplay) {
						this.innerAudioContext.pause()
						this.isplay = false
					} else {
						this.innerAudioContext.src = this.voicePath;
						this.innerAudioContext.play();
						this.isplay = true
					}
				} else {
					this.$tools.toast('音频暂未提交！');
				}
			},
			submit() {
				this.$emit('submit', this.voicePath)
			},
			/**
			 * 指定上传某个文件
			 * @param {Object} name 带后缀名的文件名称
			 */
			resetUpload(name) {
				this.$refs['lsjUpload'].upload(name);
			},
			/**
			 * 移除某个文件
			 * @param {Object} name 带后缀名的文件名称
			 */
			clear(name) {
				// name=指定文件名，不传name默认移除所有文件
				this.$refs['lsjUpload'].clear();
				this.voicePath = ''
			}
		}
	}
</script>

<style lang="less">
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 130rpx;
		line-height: 130rpx;
		text-align: center;
		font-size: 32rpx;
		background-color: #3F536E;
		color: #fff;
		z-index: 9999;
	}

	.flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.inputs {
		height: 100rpx;
		border-bottom: 1rpx solid #808080;
	}

	.padding {
		padding-top: 30rpx;
		padding-left: 30rpx;
		padding-bottom: 50rpx;
	}

	.tab {
		display: flex;
		padding: 30rpx;
	}

	.tab view {
		height: 100rpx;
		line-height: 100rpx;
		flex: 1;
		text-align: center;
		border: 1rpx solid #2C405A;
	}

	.btn {
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #fff;
	}

	.ts {
		line-height: 2em;
	}

	.nbtn {
		margin: 100rpx 50rpx;
	}

	.btnBox {
		position: fixed;
		bottom: 60rpx;
		width: 94vw;
		left: 3vw;
		display: flex;
		justify-content: space-between;

		.btn {
			width: 45vw;
			background: #f5f7fa;
			border-radius: 20rpx;
			text-align: center;
			height: 100rpx;
			line-height: 100rpx;
		}

		.btn1 {
			background-color: #6a8bff;
		}

		.btn2 {
			background-color: #5ac725;
		}
	}
</style>